package com.aiyige.base.api.httpinterceptor;

import com.aiyige.model.AiyigeExceptionModel;
import com.aiyige.utils.crash.CrashUtils;
import com.alibaba.fastjson.JSON;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class CrashReportInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        try {
            Response response = chain.proceed(request);
            if (response.code() >= 500) {
                String json = response.body().string();
                response = response.newBuilder()
                        .body(ResponseBody.create(MediaType.parse("text/plain"), json))
                        .build();
                String serverErrorDetail = "服务器异常告警：\nresponseCode:" + response.code() + "\n请求地址："
                        + request.url().toString() + "\n" + json;
                CrashUtils.getInstance().netSubmitLog(AiyigeExceptionModel.type_server_error_500, serverErrorDetail, AiyigeExceptionModel.rating_4);
            }
            return response;
        } catch (Exception e) {
            String serverErrorDetail = "服务器连接异常" + "\n请求地址："
                    + request.url().toString();
            CrashUtils.getInstance().netSubmitLog(AiyigeExceptionModel.type_network_timeout, serverErrorDetail, AiyigeExceptionModel.rating_4);
            throw new IOException(e.getMessage());
        }
    }
}
